package com.horse.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.os.Environment;

public class Downloader {

	public static void downloadFile(String directoryName, String fileName, String url,
			Context context) throws Exception {
		File file = getFile(directoryName, fileName, context);
		if (!file.exists()) {
			try {
				URL u = new URL(url);
				HttpURLConnection c = (HttpURLConnection) u.openConnection();
				c.setConnectTimeout(5000);
				c.setRequestMethod("GET");
				c.connect();
				if (c.getResponseCode() == HttpURLConnection.HTTP_OK) {
					InputStream in = c.getInputStream();
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					byte[] buffer = new byte[1024];
					int len1 = 0;
					while ((len1 = in.read(buffer)) != -1) {
						if (len1 > 0) {
							baos.write(buffer, 0, len1);
						}
					}
					buffer = baos.toByteArray();
					baos.close();
					try {
						if (buffer != null && buffer.length > 0) {
							FileOutputStream f = new FileOutputStream(file);
							f.write(buffer);
							f.close();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}

					in.close();
					c.disconnect();
				} else {
					c.disconnect();

				}
			} catch (Exception e) {
				e.printStackTrace();

			}
		}
	}
	
	public static final File ROOT = Environment.getExternalStorageDirectory();
	
	public static final File getFile(String directoryName, String fileName, Context context) {
		File ret = null;
		try {
			File file = new File(ROOT, "horse360/" + directoryName + "/");
			if (!file.exists()) {
				file.mkdirs();
			}
			ret = new File(file, fileName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}
	
	public static File[] getFileList(String direcotoryName) {
		File file = new File(ROOT, "horse360/" + direcotoryName);
		return file.listFiles(new FilenameFilter() {

			@Override
			public boolean accept(File file, String name) {
				if (name.endsWith(".png")) {
					return true;
				}
				return false;
			}
		});
	}
	
	public static File[] getAllFile() {
		File file = new File(ROOT, "horse360/");
		return file.listFiles(new FilenameFilter() {

			@Override
			public boolean accept(File file, String name) {
				if (name.endsWith(".png")) {
					return true;
				}
				return false;
			}
		});
	}
	
}
